﻿/**
 * Created by zhoujinwei on 2016/5/23.
 */

var isChinamobileSelect=0;

//默认按员工编号由小到大排列;
var nbRank = '';

$(function () {
    //实例化一个加载表格对象
    searchUserList(1);
    searchDeptList();
    searchVendorList();
    searchRoleList();
    //获取用户对象
    // var userInfo=JSON.parse(localStorage.getItem("userInfo"));
});


//加载部门下拉框
function searchDeptList(){
    $("#department").empty();
    // PostForm("/cwp/front/sh/dept!execute", "uid=c001", "", ResultDept, '');
    $.getJSON('/cwp/src/json/user/user_dept_c001.json',function(data){
        ResultDept(data);
    })
}

//加载角色下拉
function searchRoleList(){
    // PostForm("/cwp/front/sh/role!execute", "uid=c008", "", getRoleList, '');
    $.getJSON('/cwp/src/json/user/user_role_c008.json',function(data){
        getRoleList(data);
    })
}

function getRoleList(result){
    if(result.returnCode=="0" && result.beans.length>0){
        for(var i=0; i<result.beans.length; i++){
            option="<option value='"+result.beans[i].roleId+"'>"+result.beans[i].roleName+"</option>"
            $(".roleList").append(option);
        }
    }
}

//加载服务公司下拉框
function searchVendorList(){
    $("#company").empty();
    // PostForm("/cwp/front/sh/company!execute", "uid=c006", "", ResultVendor, '');
    $.getJSON('/cwp/src/json/user/user_company_c006.json',function(data){
        ResultVendor(data);
    })
}
//查询部门成功回调函数
function ResultDept(result) {
    if (result.returnCode == '0') {
        var option = "<option name='' value=''>请选择</option>";
        for(var i=0;i<result.beans.length;i++){
            var department = result.beans[i];
            var deptId = department.deptId;
            var deptName = department.deptName;
            var str = "<option value='"+deptId+"'>"+deptName+"</option>"
            option+=str;
        }
        $("#department").append(option);
    }
}
//查询供应商成功回调函数
function ResultVendor(result) {
    if (result.returnCode == '0') {

        var option = "<option name='' value=''>请选择</option>";
        for(var i=0;i<result.beans.length;i++){
            var company = result.beans[i];
            var companyId = company.companyId;
            var companyName = company.companyName;
            var str = "<option value='"+companyId+"'>"+companyName+"</option>"
            option+=str;
        }
        $("#company").append(option);
    }
}
//请求成功，执行回调函数拼接表格信息
function successResultArrived(result) {
    //拼接表头html
    if(isChinamobileSelect=='0'){
        var thead="<thead>"+
            "<tr>"+
            "<th><input class='selectAll' type='checkbox' value='' id='selectAll'></th>"+
            "<th><span style='padding: 5px 10px 0 0;float: left;'>员工编号</span><span style='float: left;'><b class='icon-arrow selectIcon icon-arrow-up' style='position:absolute;z-index: 10;'></b></br><b style='position:absolute;z-index: 20;top: 13px;background: white;width: 20px;height: 10px;'></b></br><b class='icon-arrow selectIcon icon-arrow-down' style='position:absolute;z-index: 10;top: 18px;'></b></span></th>"+
            "<th>用户名</th>"+
            //"<th>卡号</th>"+
            "<th style='min-width:56px'>姓名</th>"+
            //"<th>邮箱</th>"+
            "<th>手机</th>"+
            "<th style='min-width:40px'>性别</th>"+
            "<th>部门</th>"+
            "<th style='width:18%'>角色</th>"+
            "<th style='min-width:40px'>状态</th>"+
            "<th style='min-width:168px'>操作</th>"+
            "</tr>"+
            "</thead>";
        //拼接表格列表html
        var tbodys = "<tbody>";
        for(var i=0;i<result.beans.length;i++){
            var user = result.beans[i];
            tbodys+="<tr>" +
                "<td><input type='checkbox' data-name='"+ user.trueName +"' data-emloyeeNo='"+user.emloyeeNo +"' data-carNo='"+user.cardNo +"' value='"+user.parkId+"' class='chkUser'></td>"+
                "<td>"+user.emloyeeNo+"</td>"+
                "<td>"+user.userName+"</td>"+
                //"<td>"+user.cardNo+"</td>"+
                "<td>"+user.trueName+"</td>"+
                //"<td>"+user.email+"</td>"+
                "<td>"+user.phone+"</td>"+
                "<td>"+(user.sex=="0"?"男":"女")+"</td>"+
                "<td>"+(user.isChinamobile=="0"?user.department:user.company)+"</td>"+
                "<td>"+(user.roleName==""?"无":user.roleName)+"</td>"+
                "<td id='status"+user.parkId+"'>"+(user.status=="0"?"正常":"冻结")+"</td>"+
                "<td>" +
                "<button class='t-btn t-btn-sm t-btn-blue t-btn-edit' onclick=updateUserInfo('"+user.parkId+"')>修改</button>"+
                "<button id='operate"+user.parkId+"' class='t-btn t-btn-sm "+(user.status=="0"?"t-btn-red":"")+"' onclick=freezeUser('"+user.parkId+"','"+user.cardNo+"','"+user.emloyeeNo+"','"+user.userName+"','"+user.trueName+"')>"+(user.status=="0"?"冻结":"解冻")+"</button>"+
                (loseStatus(user.cardStatusDictdataId).out!="已退卡"?"<a style="+user.style2+" class='t-btn t-btn-sm t-btn-blue t-btn-edit btn-reportloss' data-id='"+user.parkId+"' data-identityCard='"+user.identityCardDES+"' data-identityCard-c='"+user.identityCard+"' data-identityCard-cmos='"+user.identityCardCMOS+"' data-cardNo='"+(user.cardNo==""?null:user.cardNo)+"' data-trueName='"+user.trueName+"' data-phone='"+user.phone+"' data-status='"+user.cardStatusDictdataId+"' data-type="+'lose'+">"+loseStatus(user.cardStatusDictdataId).lose+"</a>":"")+
                (loseStatus(user.cardStatusDictdataId).out!="已退卡"?"<a class='t-btn t-btn-sm t-btn-blue t-btn-edit btn-reportloss' data-id='"+user.parkId+"' data-identityCard='"+user.identityCardDES+"'  data-identityCard-c='"+user.identityCard+"' data-identityCard-cmos='"+user.identityCardCMOS+"' data-cardNo='"+(user.cardNo==""?null:user.cardNo)+"' data-trueName='"+user.trueName+"' data-phone='"+user.phone+"' data-status='"+user.cardStatusDictdataId+"' data-type="+'back'+">"+loseStatus(user.cardStatusDictdataId).out+"</a>":"<div class='t-tag t-btn-sm'>已退卡</div>")+
                "</td>"+
                "</tr>";
        }
    }
    else{
        var thead="<thead>"+
            "<tr>"+
            "<th><input class='selectAll' type='checkbox' value='' id='selectAll'></th>"+
            "<th>姓名</th>"+
            "<th>一卡通编号</th>"+
            "<th>手机</th>"+
            "<th>性别</th>"+
            "<th>服务公司</th>"+
            "<th>角色</th>"+
            "<th>状态</th>"+
            "<th>操作</th>"+
            "</tr>"+
            "</thead>";
        //拼接表格列表html
        var tbodys = "<tbody>";
        for(var i=0;i<result.beans.length;i++){
            var user = result.beans[i];
            // var user_2 = JSON.stringify(user);
            tbodys+="<tr>" +
                "<td><input type='checkbox' data-name='"+ user.trueName +"' data-emloyeeNo='-1' data-carNo='"+user.cardNo +"' value='"+user.parkId+"' class='chkUser'></td>"+
                "<td>"+user.trueName+"</td>"+
                "<td>"+user.cardNo+"</td>"+
                "<td>"+user.phone+"</td>"+
                "<td>"+(user.sex=="0"?"男":"女")+"</td>"+
                "<td>"+(user.isChinamobile=="0"?user.department:user.company)+"</td>"+
                "<td>"+(user.roleName==""?"无":user.roleName)+"</td>"+
                "<td id='status"+user.parkId+"'>"+(user.status=="0"?"正常":"冻结")+"</td>"+
                "<td>" +
                "<button class='t-btn t-btn-sm t-btn-blue t-btn-edit' onclick=updateUserInfo('"+user.parkId+"')>修改</button>"+
                "<button id='operate"+user.parkId+"' class='t-btn t-btn-sm "+(user.status=="0"?"t-btn-red":"")+"' onclick=freezeUser('"+user.parkId+"','"+user.cardNo+"','-1','"+user.userName+"','"+user.trueName+"')>"+(user.status=="0"?"冻结":"解冻")+"</button>"+
                (loseStatus(user.cardStatusDictdataId).out!="已退卡"?"<a class='t-btn t-btn-sm t-btn-blue t-btn-edit btn-reportloss' data-identityCard='"+user.identityCardDES+"'  data-identityCard-c='"+user.identityCard+"' data-identityCard-cmos='"+user.identityCardCMOS+"' data-id='"+user.parkId+"' data-cardNo='"+(user.cardNo==""?null:user.cardNo)+"' data-trueName='"+user.trueName+"' data-phone='"+user.phone+"' data-status='"+user.cardStatusDictdataId+"' data-type="+'lose'+">"+loseStatus(user.cardStatusDictdataId).lose+"</a>":"")+
                (loseStatus(user.cardStatusDictdataId).out!="已退卡"?"<a class='t-btn t-btn-sm t-btn-blue t-btn-edit btn-reportloss' data-identityCard='"+user.identityCardDES+"'  data-identityCard-c='"+user.identityCard+"' data-identityCard-cmos='"+user.identityCardCMOS+"' data-id='"+user.parkId+"' data-cardNo='"+(user.cardNo==""?null:user.cardNo)+"' data-trueName='"+user.trueName+"' data-phone='"+user.phone+"' data-status='"+user.cardStatusDictdataId+"' data-type="+'back'+">"+loseStatus(user.cardStatusDictdataId).out+"</a>":"<div class='t-tag t-btn-sm'>已退卡</div>")+
                "</td>" +
                "</tr>";
        }
    }
    tbodys+= "</tbody>";
    //显示表格html
    if(isChinamobileSelect=='0'){
        $("#tabUser").html(thead+tbodys);
        if(nbRank == '0'){
            $("#tabUser .icon-arrow-down").addClass("selected");
            $("#tabUser .icon-arrow-up").removeClass("selected");
        }else if(nbRank == '1'){
            $("#tabUser .icon-arrow-up").addClass("selected");
            $("#tabUser .icon-arrow-down").removeClass("selected");
        }
    }else{
        $("#tabUserService").html(thead+tbodys);
    }

    $('.btn-reportloss').each(function (i,v) {
        if($(this).attr('data-status') == 'null'){
            if($(this).attr('data-type') == 'back'){
                $(this).css({"display":"none"})
            }else{
                $(this).attr("class","t-tag t-btn-sm").css({'cursor':"default"});
                $(this).removeClass('t-btn-edit');
            }
        }
    })
}

//挂失 退卡确认
var canClick = true;
var user;
var _selfBtn;
$(document).on("click",".btn-reportloss",function(){
    _selfBtn = $(this);
    if(!canClick) {
        _selfBtn.css({
            background:'gray'
        })
        return false;
    }
    var status = $(this).attr('data-status');
    var type = $(this).attr('data-type');
    if(status == 'null'){
        return false;
    }
    if(status == '5001004'){
        return false
    }
    if(status == '5001003'&&type === 'back'){
        return false;
    }

    !function () {
        if(type === 'lose') {
            $('#modalCard').find('.modal-title').html('一卡通挂失');
            //$('#modalCard').find('.if').html('是否确认一卡通挂失？');
            u = 'u018';
            u2 = 'u019';
        }else{
            $('#modalCard').find('.modal-title').html('一卡通退卡');
            //$('#modalCard').find('.if').html('是否确认一卡通退卡？');
            u = 'u016';
            u2 = 'u017'
        }
    }();
    if(status == '5001002'&&type === 'lose'){
        $('#modalCard').find('.modal-title').html('一卡通解挂');
        //$('#modalCard').find('.if').html('是否确认一卡通解挂？');
        u = 'u020';
        u2 = 'u021'
    }
    user = {
        uid1:u,
        uid2:u2,
        parkId:$(this).attr('data-id'),
        cardNo:$(this).attr('data-cardNo'),
        trueName:$(this).attr('data-trueName'),
        phone:$(this).attr('data-phone'),
        identityCard:$(this).attr('data-identityCard'),
        identityCardC:$(this).attr('data-identityCard-c'),
        identityCardCMOS:$(this).attr('data-identitycard-cmos')
    };
    //查询余额
    if(user.cardNo ==undefined || user.cardNo=="" || user.cardNo=="null"){
        tipModal("icon-cross","该用户无一卡通编号");
        return;
    }//挂失
    else if(type === 'lose'){
        $('#modalCard .FWalletMoney').hide();
        $('#modalCard .FSubMoney').hide();
        $("#btnWithdram").addClass("hide");
        $("#btnConfirmCard").removeClass("hide");
        $("#chkModifyCard")[0].checked=false;
        $(".newCardNo").hide();
        $("#newCard").val("");
        $("#newCardTip").attr("class","").html("");
        $(".isModifyCard").show();
    }
    else if(type =="back"){
        $('#modalCard .FWalletMoney').show().find("p").html("");
        $('#modalCard .FSubMoney').show().find("p").html("");
        $(".isModifyCard").hide();
        $(".newCardNo").hide();
        $("#modalLoading .tip-info").html("正在查询余额，请稍等...");
        $("#modalLoading").modal({//启用modal ID
            keyboard: true,
            backdrop: 'static'
        }).on('show.bs.modal', centerModal());
        $(window).on('resize', centerModal());
        getBanlance(user.cardNo);
    }
    $('#modalCard .name p').html(user.trueName);
    $('#modalCard .phone p').html(user.phone);
    $('#modalCard .cardNo p').html((user.cardNo==undefined?"":user.cardNo));
    $("#modalCard").modal({//启用modal ID
        keyboard: true,
        backdrop: 'static'
    }).on('show.bs.modal', centerModal());
    $(window).on('resize', centerModal());
});

//挂失换卡切换
$("#chkModifyCard").on("click",function(){
    var newCardNo=$(".newCardNo");
    if($(this)[0].checked==true){
        validatorCard();
        newCardNo.show();
    }
    else{
        newCardNo.hide();
        $("#newCard").val("");
        $("#newCardTip").attr("class","").html("");
    }
});
//一卡通挂失换卡 卡号验证
function validatorCard() {
    $.formValidator.initConfig({
        validatorGroup: "3",
        formid: "frmMainCard", onerror: function (msg) {
            return false;
        }, onsuccess: function () {
            return true;
        }
    });
    $("#newCard").formValidator({
        validatorGroup: "3",
        onshow: "请输入一卡通编号",
        onfocus: "请输入一卡通编号",
        oncorrect: "&nbsp;"
    }).InputValidator({
        min: 8,
        max: 20,
        onempty: "请输入一卡通编号",
        onerror: "一卡通编号的长度为8-20个字符" //'HAHA'
    }).RegexValidator({
        regexp: "cardNo",
        datatype: "enum",
        onerror: "请输入正确的一卡通编号"
    }).FunctionValidator({
        fun: function (val, elem) {
            var htmlObj = $.ajax({
                type: "post",
                url: "/cwp/front/sh/user!execute",
                beforeSend: function (requests) {
                    requests.setRequestHeader("platform", "pc");
                },
                async: false,
                dataType: "json",
                data: {
                    uid: "u008",
                    userId: userId,
                    cardNo: val
                }
            });
            var result = JSON.parse(htmlObj.responseText);
            if (result.returnCode == "0") {
                return true;
            } else {
                return "该一卡通编号已添加";
            }
        }
    });
}

//通过卡号查询余额
function getBanlance(cardNo){
    PostForm("/cwp/front/sh/pay!execute", "uid=P024&cardNo="+cardNo, "", successResultBanlance, failedResultBanlance);
}

function successResultBanlance(result){
    $("#modalLoading").modal("hide");
    if(result.returnCode=="0"){
        var FWalletMoney = result.bean.FWalletMoney;
        // var FSubMoney = result.bean.FSubMoney;
        $('#modalCard .FWalletMoney p').html(result.bean.FWalletMoney);
        $('#modalCard .FSubMoney p').html(result.bean.FSubMoney);
        if(FWalletMoney == "0.0"){
            //$('#modalCard').find('.if').html('是否确认一卡通退卡？');
            $('#modalCard').find('.modal-title').html('一卡通退卡');
            $("#btnConfirmCard").removeClass("hide");
            $("#btnWithdram").addClass("hide");
        }else{
            //$('#modalCard').find('.if').html('是否确认一卡通支取？');
            $('#modalCard').find('.modal-title').html('一卡通支取');
            $("#btnConfirmCard").addClass("hide");
            $("#btnWithdram").removeClass("hide");
        }
    }
    else if(result.returnCode=="-9999"){
        tipModal("icon-cross","用户余额查询失败");
    }else{
        tipModal("icon-cross",(result.returnMessage==""?"一卡通账号不存在":result.returnMessage));
    }
}

//余额查询错误回调
function failedResultBanlance(result){
    $("#modalLoading").modal("hide");
}

//支取事件
$("#btnWithdram").on("click",function(){
    $("#modalLoading .tip-info").html("正在支取，请稍等...");
    $("#modalLoading").modal({//启用modal ID
        keyboard: true,
        backdrop: 'static'
    }).on('show.bs.modal', centerModal());
    $(window).on('resize', centerModal());
    PostForm("/cwp/front/sh/pay!execute", "uid=P030&cardNo=" + user.cardNo, "", takeOutMoney, '');
});

//支取回调
function takeOutMoney(result){
    $("#modalLoading").modal("hide");
    if(result.returnCode==0){
        PostForm("/cwp/front/sh/pay!execute", "uid=P024&cardNo="+user.cardNo, "", function(res){
            if(res.returnCode=="0"){
                $('#modalCard .FWalletMoney p').html(res.bean.FWalletMoney);
                $('#modalCard .FSubMoney p').html(res.bean.FSubMoney);
                tipModal("icon-checkmark", "支取成功");
                //$('#modalCard').find('.if').html('是否确认一卡通退卡？');
                $('#modalCard').find('.modal-title').html('一卡通退卡');
                $("#btnConfirmCard").removeClass("hide");
                $("#btnWithdram").addClass("hide");
            }
            else if(result.returnCode=="-9999"){
                tipModal("icon-cross","用户余额查询失败");
            }else{
                tipModal("icon-cross",(result.returnMessage==""?"一卡通账号不存在":result.returnMessage));
            }

        }, '');
    }
    else if(result.returnCode=="-9999"){
        tipModal('icon-cross',"支取失败");
    }
    else{
        tipModal('icon-cross',result.returnMessage);
    }
}

//确认点击事件
$('#btnConfirmCard').on('click',function () {
    //判断卡号是否通过
    if($("#chkModifyCard")[0].checked==true) {
        if (!$.formValidator.IsOneValid("newCard")) {
            return false;
        }
    }
    canClick = false;
    _selfBtn.css({
        background:'gray'
    });
    $('#modalCard').modal('hide');
    if(user.cardNo==""||user.cardNo==undefined){
        tipModal("icon-info2","该用户无一卡通");
    }
    else{
        var newCard = $("#newCard").val();
        //解挂-换卡
        if(newCard!="" && $("#chkModifyCard")[0].checked==true &&user.uid1=="u020"){
            PostForm("/cwp/front/sh/pay!execute", "uid=P031&oldCard=" + user.cardNo+"&newCard="+newCard+"&identityCard="+user.identityCardCMOS, "post",
                function(result){//成功回调
                    canClick = true;
                    _selfBtn.css({
                        background:'#4b9ff5'
                    });
                    if(result.returnCode == '0') {
                        tipModal('icon-checkmark',"换卡成功");
                    }else if(result.returnCode=="-9999"){
                        tipModal("icon-cross","换卡失败");
                    }else{
                        tipModal('icon-cross',result.returnMessage);
                    }
                    isPostBack=true;
                    searchUserList(1);
                }, function(result){//失败回调
                    canClick = true;
                    _selfBtn.css({
                        background:'#4b9ff5'
                    })
                    tipModal('icon-cross',"请求超时:请检查网络");
                    isPostBack=true;
                    searchUserList(1);
                });
        }
        else {
            $.ajax({
                url: '/cwp/front/sh/user!execute',
                beforeSend: function (requests) {
                    requests.setRequestHeader("platform", "pc");
                },
                type: 'get',
                timeout: 10000,
                data: {
                    uid: user.uid1,
                    userId: localStorage.getItem("parkId"),
                    parkId: user.parkId,
                    cardNo: user.cardNo,
                    identityCard: user.identityCard,
                    rid: Math.random()
                },
                success: function (res) {
                    if (res.returnCode == '0') {

                        //同步本地数据
                        var middlemanToken = res.bean.middlemanToken;
                        if (middlemanToken == "undefined") {
                            middlemanToken = " ";
                        }


                        $.ajax({
                            url: '/cwp/front/sh/user!execute',
                            beforeSend: function (requests) {
                                requests.setRequestHeader("platform", "pc");
                            },
                            type: 'get',
                            timeout: 10000,
                            data: {
                                uid: user.uid2,
                                userId: localStorage.getItem("parkId"),
                                parkId: user.parkId,
                                cardNo: user.cardNo,
                                cardBalance: res.object,
                                rid: Math.random(),
                                middlemanToken: middlemanToken
                            },
                            success: function (json) {
                                //挂失-换卡
                                if (newCard != "" && $("#chkModifyCard")[0].checked == true) {
                                    PostForm("/cwp/front/sh/pay!execute", "uid=P031&oldCard=" + user.cardNo + "&newCard=" + newCard + "&identityCard=" + user.identityCardCMOS, "post",
                                        function (result) {//成功回调
                                            canClick = true;
                                            _selfBtn.css({
                                                background: '#4b9ff5'
                                            });
                                            if (result.returnCode == '0') {
                                                tipModal('icon-checkmark', "换卡成功");
                                            } else if (result.returnCode == "-9999") {
                                                tipModal("icon-cross", "换卡失败");
                                            } else {
                                                tipModal('icon-cross', result.returnMessage);
                                            }
                                            isPostBack = true;
                                            searchUserList(1);
                                        }, function (result) {//失败回调
                                            canClick = true;
                                            _selfBtn.css({
                                                background: '#4b9ff5'
                                            })
                                            tipModal('icon-cross', "请求超时:请检查网络");
                                            isPostBack = true;
                                            searchUserList(1);
                                        });
                                } else {
                                    canClick = true;
                                    _selfBtn.css({
                                        background: '#4b9ff5'
                                    });
                                    if (json.returnCode == '0') {
                                        tipModal('icon-checkmark', json.returnMessage);
                                        if (_selfBtn.text == "退卡") {
                                            _selfBtn.after("<div class='t-tag t-btn-sm'>已退卡</div>");
                                            _selfBtn.parent().find(".btn-reportloss").remove();
                                        } else {
                                            //清空智能门禁
                                            clearIntelligentGuard();

                                            _selfBtn.attr('data-status', json.object);
                                            _selfBtn.text(loseStatus(json.object)[_selfBtn.attr('data-type')]);
                                        }
                                        isPostBack = true;
                                        searchUserList(1);
                                    } else {
                                        tipModal('icon-cross', json.returnMessage);
                                    }
                                }
                            },
                            error: function () {
                                canClick = true;
                                _selfBtn.css({
                                    background: '#4b9ff5'
                                })
                                tipModal('icon-cross', "请求超时:请检查网络");
                            }
                        });
                    }
                    else {
                        canClick = true;
                        _selfBtn.css({
                            background: '#4b9ff5'
                        })
                        tipModal('icon-cross', res.returnMessage);
                    }
                },
                error: function () {
                    canClick = true;
                    _selfBtn.css({
                        background: '#4b9ff5'
                    })
                    tipModal('icon-cross', "请求超时:请检查网络");
                }
            });
        }
    }
});

var clearIntelligentGuard = function () {
    PostForm("/cwp/front/sh/user!execute", "uid=u029&parkId=" + user.parkId + "&code=1", "", function (result) {
        if (result.returnCode != "0") {
            tipModal("icon-cross", "智能门禁保存失败");
        }
    });
};

function loseStatus(status) {
    var a = {};
    if(status == 'null') {//accessOldZ
        a.lose = '无卡';
        a.out = '无卡'; //btnEditGuard
    }else if(status == '5001001') {
        a.lose = '挂失';
        a.out = '退卡';
    }else if(status == '5001002'){
        a.lose = '解挂';
        a.out = '退卡';
    }else if (status == '5001003'){
        a.lose = '挂失';
        a.out = '已退卡';
    }else if(status == '5001004') {
        a.lose = '已禁用';
        a.out = '已禁用';
    }
    return a;
}
//通过选项卡切换内部/外部用户列表
$("#myTabs li").on("click",function(){
    //初始化第一次加载
    isPostBack=true;
    //选择加载内部/外部用户列表
    isChinamobileSelect=$(this).index();
    $("#hidDeptId").val("");
    $("#company").val("");
    $("#keyword").val("");
    searchUserList(1);

});

//加载页面列表
function searchUserList(pageIndex) {
    //获取搜索先关条件 默认搜索数据为空
    //var department=$("#department").val();
    /*
     *实例化加载表格数据分页对象
     *@id实例化对象ID用于分页是指定对象数据
     *@layerID显示数据所在DIV的ID
     *@url获取数据请求地址
     *@parameters通过url传递参数
     *@currentPage当前页
     *@pageSize每页显示多少条数据
     *@successFunction请求成功回调函数
     *@failedFunction请求失败回调函数
     */
    var tabID="";
    var loaderObj="";
    var loaderUserTab;
    if(isChinamobileSelect==0) {
        loaderObj="loaderUserTab";
        displayTabId="tabUser";
        var str = "frmSearch";

        $.getJSON('/cwp/src/json/user/user_list_u002.json',function(data){
            loaderUserTab = new LoaderTable(loaderObj,displayTabId,"/cwp/front/sh/user!execute","uid=u002&isChinamobile=0&emloyeeNoSort="+nbRank,pageIndex,10,successResultArrived,"",str);
            loaderUserTab.loadSuccessed(data);
        });
    }
    else {
        loaderObj="loaderTabUserService";
        displayTabId="tabUserService";
        var str = "frmSearch1";
        $.getJSON('/cwp/src/json/user/user_list_u002.json',function(data){
            loaderUserTab = new LoaderTable(loaderObj,displayTabId,"/cwp/front/sh/user!execute","uid=u002&isChinamobile="+isChinamobileSelect+"&emloyeeNoSort=",pageIndex,10,successResultArrived,"",str);
            loaderUserTab.loadSuccessed(data);
        });
    }
    // loaderUserTab.Display();
}

//// 操作 冻结/解冻 状态
//function freezeUser(parkId) {
//    var status = $("#status" + parkId).html();
//    $("#hidUserId").val(parkId);
//
//    if (status == "正常") {
//        PostForm("/cwp/front/sh/user!execute", "uid=u005&parkId=" + parkId + "&code=" + 1, "", successResultFreezeUser, '');
//        $("#status" + parkId).html("冻结");
//        $("#operate" + parkId).html("解冻").removeClass("t-btn-red");
//    } else {
//        PostForm("/cwp/front/sh/user!execute", "uid=u005&parkId=" + parkId + "&code=" + 0, "", successResultFreezeUser, '');
//        $("#status" + parkId).html("正常");
//        $("#operate" + parkId).html("冻结").addClass("t-btn-red");
//    }
//}
////请求成功回调函数
//function successResultFreezeUser(result) {
//    switch (result.returnCode) {
//        case "0":
//            tipModal("icon-checkmark", "修改成功");
//            break;
//        case "2":
//            tipModal("icon-cross", "修改失败");
//            break;
//        case "-9999":
//            tipModal("icon-cross", "修改失败");
//            break;
//    }
//}


//模糊查询 点击事件
$(".btnSearch").on("click",function(){
    var searchType = "";
    var searchContent =  "";
    if(isChinamobileSelect==0){
        searchType = $("#searchType").val();
        searchContent = $("#searchContent").val();
    }else{
        searchType = $("#searchTypeExt").val();
        searchContent = $("#searchContentExt").val();
    }

    if((searchType!="") && (searchContent == "" || searchContent ==undefined)){
        tipModal("icon-info2", "请输入搜索关键字");
        return;
    }
    else if((searchContent != "" || searchContent ==undefined) && (searchType == "")){
        tipModal("icon-info2", "请选择查询类型");
        return;
    }

    isPostBack=true;
    nbRank = '';
    searchUserList(1);

});

//当前页，加载容器
function paginationCallback(page_index){
    if(!isPostBack) {
        searchUserList(page_index+1);
    }
}



//查询所有部门
$(function(){
    initDeptTree();
});

function initDeptTree(){
    // PostForm("/cwp/front/sh/dept!execute", "uid=c007", "", getDeptTree, '');
    $.getJSON('/cwp/src/json/user/user_dept_c007.json',function(data){
        getDeptTree(data);
    })
}

//获取数据初始化部门树
function getDeptTree(result){
    if(result.returnCode=="0"){
        //配置组织结构树
        var setting = {
            view: {
                addHoverDom: addHoverDom,         //鼠标移入显示自定义按钮
                removeHoverDom: removeHoverDom,   //鼠标移出隐藏自定义按钮
                showIcon: false,                 //隐藏节点图标
                selectedMulti: false             //设置是否允许同时选中多个节点
            },
            edit: {
                enable: true//是否处于编辑状态
            },
            data: {
                simpleData: {
                    enable: true
                }
            },
            callback: {
                beforeEditName: beforeEditName,   //编辑回调事件
                beforeRemove: beforeRemove,       //删除回调事件
                beforeClick:beforeClick
            }
        };
        var zNodes=JSON.parse(result.object);
        $.fn.zTree.init($("#treeOrg"), setting, zNodes);
        var zTree = $.fn.zTree.getZTreeObj("treeOrg");
        zTree.setting.edit.removeTitle = "删除";
        zTree.setting.edit.renameTitle = "编辑";
        if(countTreeId!=undefined && countTreeId!=""){
            var getTreeNode=zTree.getNodeByTId(countTreeId);
            //默认选中节点
            zTree.selectNode(getTreeNode);
            //默认展开节点
            zTree.expandNode(getTreeNode,true);
        }

    }
}

function beforeEditName(treeId, treeNode) {
    var zTree = $.fn.zTree.getZTreeObj("treeOrg");
    zTree.selectNode(treeNode);
    setTimeout(function() {
        $("#hidModalDeptId").val(treeNode.id);
        countTreeId=treeNode.tId;
        // PostForm("/cwp/front/sh/dept!execute", "uid=c004", "", getDeptbyId, '',"frmMainDept");
        $.getJSON('/cwp/src/json/user/user_dept_c004.json',function(data){
            getDeptbyId(data);
        })
    }, 0);
    return false;
}

//显示欲编辑部门信息
function getDeptbyId(result){
    if(result.returnCode=="0"){
        displayDeptModal();
        $("#hidModalDeptId").val(result.object.deptId);
        $("#hidDeptPId").val(result.object.parentId);
        $("#deptName").val(result.object.deptName);
        $("#type").val(result.object.type);
        $("#orderNum").val(result.object.orderNum);
        $("#modalAddDeptTitle").html("编辑部门");
    }
    else if(result.returnCode=="-9999"){
        tipModal('icon-cross',"获取部门信息失败");
    }
    else{
        tipModal('icon-cross',result.returnMessage);
    }
}

var countTreeNode;
function beforeRemove(treeId, treeNode) {
    var zTree = $.fn.zTree.getZTreeObj("treeOrg");
    zTree.selectNode(treeNode);
    countTreeNode=treeNode;
    $("#modalDelDept").modal({//启用modal ID
        keyboard: true,
        backdrop: 'static'
    }).on('show.bs.modal', centerModal());
    $(window).on('resize', centerModal());
    return false;
}

//删除节点
$("#btnDeleteDept").on("click",function(){
    // PostForm("/cwp/front/sh/dept!execute", "uid=c010&deptId="+countTreeNode.id, "", delDeptbyId, "","deptTree");
    $.getJSON('/cwp/src/json/user/user_dept_c010.json',function(data){
        delDeptbyId(data);
    })
});

//删除部门回调
function delDeptbyId(result){
    $("#modalDelDept").modal("hide");
    if(result.returnCode=="0"){
        var treeObj = $.fn.zTree.getZTreeObj("treeOrg");
        treeObj.removeNode(countTreeNode);
        tipModal("icon-checkmark", "删除成功");
        initDeptTreeModal();
        initModalBatDept();

    }
    else if(result.returnCode=="-9999"){
        tipModal('icon-cross',"删除部门失败");
    }
    else{
        tipModal('icon-cross',result.returnMessage);
    }
}


//树形节点点击添加
var countTreeId;
function addHoverDom(treeId, treeNode) {
    var sObj = $("#" + treeNode.tId + "_span");
    if (treeNode.editNameFlag || $("#addBtn_"+treeNode.tId).length>0) {
        return;
    }
    var addStr = "<span class='button add' id='addBtn_" + treeNode.tId + "' title='新增部门'></span>";
    sObj.after(addStr);
    var btn = $("#addBtn_"+treeNode.tId);
    if (btn) {
        btn.bind("click", function(){
            var zTree = $.fn.zTree.getZTreeObj("treeOrg");
            zTree.selectNode(treeNode);
            countTreeId=treeNode.tId;
            displayDeptModal();
            $("#modalAddDeptTitle").html("新增部门");
            $("#hidDeptPId").val(treeNode.id);
            return false;
        });
    }
};

function removeHoverDom(treeId, treeNode) {
    $("#addBtn_"+treeNode.tId).unbind().remove();
};

//显示部门表单弹出框
function displayDeptModal(){
    resetDeptFrom();
    $("#modalAddDept").modal({//启用modal ID
        keyboard: true,
        backdrop: 'static'
    }).on('show.bs.modal', centerModal());
    $(window).on('resize', centerModal());
}



function beforeClick(treeId, treeNode){
    var deptId=treeNode.id;
    $("#hidDeptId").val(deptId);
    isPostBack=true;
    searchUserList(1);
}

//班组表单验证
$(function(){
    $.formValidator.initConfig({
        validatorGroup:"3",
        formid: "frmMainDept", onerror: function (msg) {
            return false;
        }, onsuccess: function () {
            return true;
        }
    });
    $("#deptName").formValidator({
        validatorGroup:"3",
        onfocus: "请输入部门名称",
        oncorrect: " "
    }).InputValidator({
        min: 4,
        max: 40,
        onempty: "请输入部门名称",
        onerror: "用户名长度为4-40个字符"
    });

    $("#type").formValidator({
        validatorGroup:"3",
        onfocus:"部门必须选择",
        oncorrect:"&nbsp;"
    }).InputValidator({
        min: 1,
        onempty: "请选择部门",
        onerror: "请选择部门"
    });

    $("#orderNum").formValidator({
        validatorGroup:"3",
        onfocus:"请选择部门级别",
        oncorrect:"&nbsp;"
    }).InputValidator({
        min: 1,
        onempty: "请选择部门级别",
        onerror: "请选择部门级别"
    });
});


$("#btnSaveDept").on("click", function () {
    if ($.formValidator.PageIsValid(3)) {
        var hidDeptId=$("#hidModalDeptId").val();
        if(hidDeptId==""){
            //新增部门
            // PostForm("/cwp/front/sh/dept!execute", "uid=c003", "", addDept,"", "frmMainDept");
            $.getJSON('/cwp/src/json/user/user_dept_c003.json',function(data){
                addDept(data);
            })
        }
        else{
            //编辑部门
            // PostForm("/cwp/front/sh/dept!execute", "uid=c005", "", editDept,"", "frmMainDept");
            $.getJSON('/cwp/src/json/user/user_dept_c005.json',function(data){
                editDept(data);
            })
        }

    }
});

//新增部门回调
function addDept(result){
    if(result.returnCode=="0"){
        $("#modalAddDept").modal("hide");
        tipModal("icon-checkmark", "保存成功");
        initDeptTree();

        initDeptTreeModal();
        initModalBatDept();

    }
    else if(result.returnCode=="-9999"){
        tipModal('icon-cross',"新增部门失败");
    }
    else{
        tipModal('icon-cross',"新增部门失败");
    }
}

//编辑部门
function editDept(result){
    if(result.returnCode=="0"){
        $("#modalAddDept").modal("hide");
        tipModal("icon-checkmark", "保存成功");
        initDeptTree();
        initDeptTreeModal();
        initModalBatDept();

    }
    else if(result.returnCode=="-9999"){
        tipModal('icon-cross',"编辑部门失败");
    }
    else{
        tipModal('icon-cross',"编辑部门失败");
    }
}

//重置部门表单
function resetDeptFrom(){
    $("#hidModalDeptId").val("");
    $("#hidDeptPId").val("");
    $("#deptName").val("");
    $("#type").val("");
    $("#orderNum").val("");
    $(".tipArea div").html("").attr("class","");
}

//全选
$(document).on("click",".selectAll",function(){
    if(this.checked==true){
        $(".chkUser").each(function(){
            this.checked=true;
        });
    }
    else{
        $(".chkUser").each(function(){
            this.checked=false;
        });
    }
});

//按员工编号进行排序
//升序
$(document).on("click",".icon-arrow-up",function(){
    if(nbRank != '1'){
        isPostBack=true;
        nbRank = '1';
        searchUserList(1);
    }
});
//降序
$(document).on("click",".icon-arrow-down",function(){
    if(nbRank != '0'){
        isPostBack=true;
        nbRank = '0';
        searchUserList(1);
    }
});